package com.ruoyi.asset.service.impl;

import com.ruoyi.asset.domain.*;
import com.ruoyi.asset.mapper.AssetCategoryMapper;
import com.ruoyi.asset.service.AssetsCategoryService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.TreeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

@Service
public class AssetsCategoryServiceImpl implements AssetsCategoryService {

    private final static Logger logger = LoggerFactory.getLogger(AssetsCategoryServiceImpl.class);

    @Resource
    private AssetCategoryMapper assetCategoryMapper;

    @Override
    public List<AssetsCategoryTreeVo> categoryTree(GetAssetsCategoryTreeVo evt) {
        List<AssetsCategoryTreeVo> treeList = new ArrayList<AssetsCategoryTreeVo>();
        try {
            List<AssetsCategoryTreeVo> list = assetCategoryMapper.categoryTree(evt);
            Iterator it = list.iterator();
            while (it.hasNext()) {
                AssetsCategoryTreeVo tree = (AssetsCategoryTreeVo) it.next();
                if (!"0".equals(tree.getParentId())) {
                    continue;
                }
                TreeUtils.createTree(list, tree, "id", "parentId", "children");
                treeList.add(tree);
            }
        } catch (Exception e) {
            logger.error("unknown error: ", e);
            throw new RuntimeException();
        }
        return treeList;
    }

    @Override
    public AssetsCategoryInfoVo categoryInfo(GetAssetsCategoryInfoVo evt) {
        return assetCategoryMapper.categoryInfo(evt);
    }

//    @Override
//    public Result<?> list(GetAssetsListVo evt) {
//        Integer total = assetCategoryMapper.findListCount(evt);
//        List<ProductListVo> list = total == 0 ? null : assetCategoryMapper.findList(evt);
//        return new Result<>(ApiResultEnum.SUCCESS, list, total);
//    }

//    @Override
//    public Result<?> get(GetAssetsInfoVo evt) {
//        ProductInfoVo productInfoVo = assetCategoryMapper.get(evt);
//        return new Result<>(ApiResultEnum.SUCCESS,productInfoVo);
//    }

    @Override
    public Integer categoryInsert(AssetsCategoryChangeVo evt) {
        //时间戳作为key值
        String timestamp = String.valueOf(System.currentTimeMillis());
        Boolean repeat = false;
        String id = "";
        String path = "";
        Integer level = 1;
        //1、判断主、子添加
        if(evt.getParentId() == null || "".equals(evt.getParentId())){
            //主添加
            //1、获取当前的id值
            id = "-" + assetCategoryMapper.getId() + "-";
            //2、设置随机路径
            do{
                path = RandomGenerator();
                repeat = assetCategoryMapper.repeatByPath(path);
            }while (repeat);
        }else {
            //子添加
            //1、设置随机id
            do{
                id = evt.getParentId() + RandomNumberGenerator() + "-";
                repeat = assetCategoryMapper.repeatById(id);
            }while (repeat);
            //2、设置随机路径
            path = assetCategoryMapper.findParentPath(evt.getParentId());
            if(path == null || "".equals(path)){
                throw new ServiceException("找不到对应的父类路径，请联系管理员！");
            }
            level = assetCategoryMapper.findLevelByParentId(evt.getParentId());
            //重置
            repeat = false;
            do{
                path = path + "-" + RandomGenerator();
                repeat = assetCategoryMapper.repeatByPath(path);
            }while (repeat);
        }
        evt.setId(id);
        evt.setLevel(level);
        evt.setPath(path);
        evt.setKey(timestamp);
        return assetCategoryMapper.categoryInsert(evt);
    }

    @Override
    public Integer categoryUpdate(AssetsCategoryChangeVo evt) {
        return assetCategoryMapper.categoryUpdate(evt);
    }

    @Override
    public Integer categoryDelete(AssetsCategoryDeleteVo evt) {
        //判断当前产品分类没有被其他产品使用
        if(assetCategoryMapper.verifyByProduct(evt) > 0){
            throw new ServiceException("设备分类已经被其他设备使用！");
        }
        return assetCategoryMapper.categoryDelete(evt);
    }

    /**
     * 生成10-9999之间的数字
     * @return
     */
    private static String RandomNumberGenerator(){
        Random random = new Random();
        int randomNumber = random.nextInt(9990) + 10;
        return String.valueOf(randomNumber);
    }

    /**
     * 根据大小英文，数字生成四位随机字符串
     * @return
     */
    private static String RandomGenerator(){
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 生成4位验证码
        for (int i = 0; i < 4; i++) {
            int randomIndex = random.nextInt(chars.length());
            char randomChar = chars.charAt(randomIndex);
            code.append(randomChar);
        }
        return code.toString();
    }

}
